import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// 获取所有论坛文章
// 获取所有论坛文章
export const getForumArticles = async () => {
  try {
    // 从 localStorage 中获取 token
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 发送 GET 请求，带上 Authorization header
    const response = await apiClient.get('/admin/api/forum_articles', {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    // console.log(response.data, 'response.datacsacascas');
    // 返回获取的文章数据
    return { success: true, articles: response.data };
  } catch (error) {
    console.error('获取论坛文章失败:', error);
    // 如果没有返回自定义的错误信息，返回通用错误信息
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 插入新论坛文章
export const postForumArticle = async (articleData) => {
  try {
    // 从 localStorage 中获取 token
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 发送 POST 请求，带上 Authorization header 和请求体
    const response = await apiClient.post('/api/forum_articles', articleData, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, articleId: response.data.articleId };
  } catch (error) {
    console.error('发布文章失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '发布失败'
    };
  }
};

// 删除文章
export const deleteArticleApi = async (articleId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 只传递 articleId，不需要 userId
    const response = await apiClient.delete(`/admin/api/articles/${articleId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return response.data;
  } catch (error) {
    console.error('删除文章失败:', error);
    return { success: false, message: error.response?.data?.error || '删除失败' };
  }
};
